﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WLW_Electricity_detection
{
    public partial class Form_串口配置 : Form
    {
        Thread serial_port_th = null;
        Thread receive_th = null;
        SynchronizationContext Assistant = null;

        public Form_串口配置()
        {
            InitializeComponent();
            Assistant = SynchronizationContext.Current;
            startThread();
            receive_startThread();
        }

        void startThread() // 线程启动函数
        {
            serial_port_th = new Thread(update_serial);
            serial_port_th.Start();
        }

        void update_serial() // 线程函数
        {
            while (true)
            {
                Thread.Sleep(100);
                Assistant.Post(updateText, null);
            }
        }

        void updateText(object obj) // 线程助手 
        {
            string[] str = SerialPort.GetPortNames();

            for (int y = 0; y < str.Length; y++)
            {
                if (comboBox_串口号.Items.Contains(str[y]) == false)
                    comboBox_串口号.Items.Add(str[y]);
            }

            for (int y = 0; y < comboBox_串口号.Items.Count; y++)
            {
                if (str.Contains(comboBox_串口号.Items[y]) == false)
                {
                    comboBox_串口号.Items.Remove(comboBox_串口号.Items[y]);
                }
            }
        }

        void receive_startThread() // 线程启动函数
        {
            receive_th = new Thread(receive);
            receive_th.Start();
        }

        void receive()
        {
            while (true)
            {
                Thread.Sleep(100);

                if (serialPort_串口号.IsOpen)
                {
                    int data_size = 0;

                    try
                    {
                        data_size = serialPort_串口号.BytesToRead;
                    }
                    catch (Exception)
                    {
                        data_size = 0;
                        MessageBox.Show("串口断开或已拔出");
                    }

                    if (data_size == 5)
                    {
                        byte[] recvBuf = new byte[5];
                        serialPort_串口号.Read(recvBuf, 0, 5); // 读取串口缓存中的数据
                        string recvStr = System.Text.Encoding.Default.GetString(recvBuf, 0, 5);
                        recvStr = unpack(recvStr); // 解包
                        if (recvStr != false.ToString())
                        {
                            Share.val = recvStr;
                            Share.val_time = DateTime.Now.ToString("HH:mm:ss");
                        }
                    }
                    serialPort_串口号.DiscardInBuffer();
                }
            }
        }

        string unpack(string val)
        {
            if (val.Length == 5)
            {
                int start = val.IndexOf("V_");

                if (start == 0)
                {
                    return val.Substring("V_".Length + start);
                }
            }
            return false.ToString();
        }

        void serialPort_Open(SerialPort obj)
        {
            obj.PortName = comboBox_串口号.Text;
            obj.BaudRate = int.Parse(comboBox_波特率.Text);
            try
            {
                obj.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("串口被占用,或不存在");
            }
            button_连接.Text = "关闭";
            label_变化灯.ForeColor = Color.Red;
        }

        void serialPort_Clear(SerialPort obj)
        {
            obj.Close();
            button_连接.Text = "打开";
            label_变化灯.ForeColor = Color.Black;
        }

        private void Form_后台_Load(object sender, EventArgs e)
        {

        }

        private void button_关闭_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void button_连接_Click(object sender, EventArgs e)
        {
            if (button_连接.Text == "打开" && comboBox_串口号.Text != "" && comboBox_波特率.Text != "")
            {
                serialPort_Open(serialPort_串口号);
            }
            else
            {
                serialPort_Clear(serialPort_串口号);
            }
        }
    }
}
